package com.icms.common.util;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.upload.UploadFile;

public class UploadUtil {

	protected final static Logger log = Logger.getLogger(UploadUtil.class);
	/********************************************************
	 *
	 * 文件上传
	 *
	 ********************************************************/

	/**
	 * 获取允许上传的文件类型
	 * 
	 * @return
	 */
	public static String getFileAllowType() {
		return PropKit.use("application.properties").get("system.allowType");
	}

	/**
	 * 获取上传文件的文件类型
	 * 
	 * @param file
	 * @return
	 */
	public static String getFileType(String fileName) {
		String type = fileName.substring(fileName.lastIndexOf(".") + 1);
		return type;
	}

	/**
	 * 检查文件类型
	 * 
	 * @param fileType
	 * @return
	 */
	public static boolean checkFileType(String fileType) {
		return getFileAllowType().indexOf(fileType.toLowerCase()) == -1;
	}

	/**
	 * 文件上传方法
	 * 
	 * @param files
	 * @param path
	 * @return
	 */
	public static Map<String, Object> uploadFile(List<UploadFile> files, String path,String fileType) {
		Map<String, Object> result = new HashMap<String, Object>();
		StringBuffer filePath = new StringBuffer();
		int counter = 0;
		long beginTime = System.currentTimeMillis();
		for (UploadFile uploadFile : files) {
			if(fileType==null){
			 fileType = getFileType(uploadFile.getFileName().toString());
			}
			String PicName = System.currentTimeMillis() + "." + fileType;
			// 检查上文件的类型
			if (!checkFileType(fileType)) {
				String newName = PathKit.getWebRootPath() + "/r/tmp/" + PicName;
				File file = new File(newName);
				uploadFile.getFile().renameTo(file);
				// 判断是是否开启七牛云存储，默认为关闭
				if (PropKit.use("application.properties").getBoolean("qiniu.on", false)) {
					log.info("文件绝对路径:" + file.getAbsolutePath());
					try {
						QiniuUtil qiniuUtil = new QiniuUtil();
						PicName = qiniuUtil.getUrl((JSON.parseObject(qiniuUtil.upload(file.getAbsolutePath(), PicName))
								.get("key").toString()));
						file.delete();
						log.info("本地文件删除完成！");
					} catch (Exception e) {
						file.delete();
						PicName = "";
						counter++;
						log.error("上传文件失败:" + e.getMessage());
					}
					filePath.append(PicName + "|");
				}
			} else {
				counter++;
				log.info("检测出系统不允许上传的文件类型！");
			}
		}
		long endTime = System.currentTimeMillis();
		log.info("上传文件" + files.size() + "个，失败：" + counter + "用时：" + (endTime - beginTime) + "毫秒");
		result.put("errorCount", counter);
		result.put("filePath", filePath.toString());
		return result;
	}

	
}
